
package org.demo.springbootdemo.Controller;

import org.demo.springbootdemo.Common.Response;
import org.demo.springbootdemo.Entity.User;
import org.demo.springbootdemo.Service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 用户控制器
 * 处理用户相关的HTTP请求
 */
@RestController
@RequestMapping("/users")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 获取所有用户
     * @return 用户列表
     */
    @GetMapping
    public Response getAllUsers() {
        List<User> users = userService.findAll();
        return Response.success(users);
    }

    /**
     * 根据ID获取用户
     * @param id 用户ID
     * @return 用户信息
     */
    @GetMapping("/{id}")
    public Response getUserById(@PathVariable Long id) {
        User user = userService.findById(id);
        return Response.success(user);
    }

    /**
     * 创建新用户
     * @param user 用户信息
     */
    @PostMapping
    public Response createUser(@RequestBody User user) {
        userService.insert(user);
        return Response.success("用户创建成功", null);
    }

    /**
     * 更新用户信息
     * @param id 用户ID
     * @param user 更新的用户信息
     */
    @PutMapping("/{id}")
    public Response updateUser(@PathVariable Long id, @RequestBody User user) {
        user.setId(id);
        userService.update(user);
        return Response.success("用户更新成功", null);
    }

    /**
     * 删除用户
     * @param id 用户ID
     */
    @DeleteMapping("/{id}")
    public Response deleteUser(@PathVariable Long id) {
        userService.delete(id);
        return Response.success("用户删除成功", null);
    }
}